﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
using System.Xml.Linq;

namespace SocialCounter.NET
{
    public class Counter
    {
        /// <summary>
        /// Get Facebook friend's count for a profile.
        /// </summary>
        /// <param name="FBProfileName">facebook profile name e.g.khandelwal.p </param>
        /// <returns>Total counts of the facebook friends</returns>
        public static string GetFacebookFriendsCount(string FBProfileName)
        {
            string fBProfileID = string.Empty;
            if (FBProfileName.Trim() == "")
            {
                throw new Exception("Parameter: FBProfileName is not provided");
            }
            try
            {
                fBProfileID = Functions.GetFBProfileID(FBProfileName);
            }
            catch (Exception exception)
            {
                return exception.ToString();
            }
            string uri = URLs.FBFQL + "select%20friend_count%20from%20user%20where%20uid=" + fBProfileID;
            try
            {
                return Convert.ToString((from elem in XElement.Load(uri).Descendants()
                                         where elem.Name.LocalName == "friend_count"
                                         select elem).First<XElement>().Value);
            }
            catch (Exception exception2)
            {
                return exception2.ToString();
            }
        }

        /// <summary>
        /// Get total number of facebook page/link likes
        /// </summary>
        /// <param name="FaceBookPageURL">Facebook page URL or link URL e.g. http://facebook.com/audi </param>
        /// <returns>Total number of likes for the page</returns>
        public static string GetFacebookLikes(string FaceBookPageURL)
        {
            if (FaceBookPageURL.Trim() == "")
            {
                throw new Exception("Parameter: FaceBookPageURL is not provided");
            }
            string uri = URLs.FBFQL + "select%20%20like_count,%20total_count,%20share_count,%20click_count%20from%20link_stat%20where%20url=%22" + FaceBookPageURL + "%22";
            try
            {
                return Convert.ToString((from elem in XElement.Load(uri).Descendants()
                                         where elem.Name.LocalName == "like_count"
                                         select elem).First<XElement>().Value);
            }
            catch (Exception exception)
            {
                return exception.ToString();
            }
        }

        /// <summary>
        /// Get total feed readers count
        /// </summary>
        /// <param name="ProfileName">Feed burner profile name e.g. MidnightProgrammer</param>
        /// <returns>Total number of feed readers</returns>
        public static string GetFeedReadersCount(string ProfileName)
        {
            if (ProfileName.Trim() == "")
            {
                throw new Exception("Parameter: ProfileName is not provided");
            }
            try
            {
                return (from item in XDocument.Load(URLs.FeedsURL + ProfileName).Descendants("entry") select item.Attribute("circulation").Value).SingleOrDefault<string>();
            }
            catch (Exception exception)
            {
                return exception.ToString();
            }
        }

        /// <summary>
        /// Get total +1 count for the given web URL
        /// </summary>
        /// <param name="WebURL">e.g. http://midnightprogrammer.net/socilcounter </param>
        /// <returns>Total number of +1 counts</returns>
        public static string GetPlusOnesCount(string WebURL)
        {
            if (WebURL.Trim() == "")
            {
                throw new Exception("Parameter: WebURL is not provided");
            }
            else
            {
                try
                {
                    string requestUriString = "https://clients6.google.com/rpc?key=AIzaSyCKSbrvQasunBoV16zDH9R33D88CeLr9gQ";
                    string s = "[{\"method\":\"pos.plusones.get\",\"id\":\"p\",\"params\":{\"nolog\":true,\"id\":\"" + WebURL + "\",\"source\":\"widget\",\"userId\":\"@viewer\",\"groupId\":\"@self\"},\"jsonrpc\":\"2.0\",\"key\":\"p\",\"apiVersion\":\"v1\"}]";
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUriString);
                    request.Method = "POST";
                    request.ContentType = "application/json-rpc";
                    request.ContentLength = s.Length;
                    Stream requestStream = request.GetRequestStream();
                    byte[] bytes = new UTF8Encoding().GetBytes(s);
                    requestStream.Write(bytes, 0, bytes.Length);
                    requestStream.Close();
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream responseStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    string input = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                    response.Close();
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    serializer.RegisterConverters(new DynamicJsonConverter[] { new DynamicJsonConverter() });
                    object obj2 = serializer.Deserialize(input, typeof(object));
                    return (string)((dynamic)obj2)[0].result.metadata.globalCounts.count.ToString().Replace(".0", "");
                }
                catch (Exception exception)
                {
                    return exception.ToString();;
                }

            }
        }

        /// <summary>
        /// Get total number of twitter followers count
        /// </summary>
        /// <param name="UserName">Twitter profile name. e.g. prashantmx</param>
        /// <returns></returns>
        public static string GetTwitterFollowersCount(string UserName)
        {
            if (UserName.Trim() == "")
            {
                throw new Exception("Parameter: UserName is not provided");
            }
            try
            {
                return (from item in XDocument.Load(URLs.TwitterURL + UserName + "&include_entities=false").Descendants("user")
                        select item.Element("followers_count").Value).SingleOrDefault<string>();
            }
            catch (Exception exception)
            {
                return exception.ToString();
            }
        }

        /// <summary>
        /// Get total number of delicious save count
        /// </summary>
        /// <param name="WebURL">Web URL. e.g. http://midnightprogrammer.net/socialcounter/ </param>
        /// <returns>Total number of delicious save count</returns>
        public static string GetDeliciousSaveCount(string WebURL)
        {
            if (WebURL.Trim() == "")
            {
                throw new Exception("Parameter: WebURL is not provided");
            }
            else
            {
                string reqWbebURL = URLs.DeliciousURL + WebURL;
                try
                {
                    string input = new WebClient().DownloadString(reqWbebURL);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    serializer.RegisterConverters(new DynamicJsonConverter[] { new DynamicJsonConverter() });
                    dynamic obj2 = serializer.Deserialize(input, typeof(object));
                    return Convert.ToString(obj2[0].total_posts);
                }
                catch (Exception)
                {
                    return "Cannot get Delicious save count for the requested URL";
                }
            }
        }

        /// <summary>
        /// Get total number of linkedin share count
        /// </summary>
        /// <param name="WebURL">Web URL. e.g.</param>
        /// <returns>Total number of linkedin share count</returns>
        public static string GetLinkedInShareCount(string WebURL)
        {
            if (WebURL.Trim() == "")
            {
                throw new Exception("Parameter: WebURL is not provided");
            }
            else
            {
                string reqWbebURL = URLs.LinkedInURL + WebURL + "&format=json";
                try
                {
                    string input = new WebClient().DownloadString(reqWbebURL);
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    serializer.RegisterConverters(new DynamicJsonConverter[] { new DynamicJsonConverter() });
                    dynamic obj2 = serializer.Deserialize(input, typeof(object));
                    return Convert.ToString(obj2.count);
                }
                catch (Exception)
                {
                    return "Cannot get LinkedIn share count for the requested URL";
                }
            }
        }


        /* string input = new WebClient().DownloadString("http://www.stumbleupon.com/services/1.01/badge.getinfo?url=http://www.treehugger.com/");
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.RegisterConverters(new DynamicJsonConverter[] { new DynamicJsonConverter() });
            dynamic obj2 = serializer.Deserialize(input, typeof(object));
            Response.Write(Convert.ToString(obj2.result.views));
         * */

    }
}

